package cn.hit.thread;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JProgressBar;
import javax.swing.JTextArea;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import cn.hit.ExecuteSqlWin;
import cn.hit.constant.HitConstants;
import cn.hit.utils.HitUtils;

public class GenerateTestDataThread extends Thread {

    private File sourceFile = null;
    private String tableName = null;
    private List<String> fieldsName = null;
    private List<List<String>> testData = null;
    private StringBuilder sql = null;
    private StringBuilder exportLog;
    private ExecuteSqlWin mainWin = null;
    private JTextArea logArea = null;
    private JProgressBar pbar = null;

    //进度条的临时变量
    private String tmpPrintValue;

    //进度条的临时变量
    private int tmpPbarValue;
    public GenerateTestDataThread(ExecuteSqlWin win){
        mainWin = win;
        sourceFile = new File(win.getImportPath().getText().trim());
        fieldsName = new ArrayList<String>();
        testData = new ArrayList<List<String>>();
        sql = new StringBuilder(HitConstants.DB_TEST_DATA_QUERY_ID_BY_NO);
        exportLog = new StringBuilder();
        logArea = win.getLogArea();
        pbar = win.getPbar();
    }

    @Override
    public void run() {
        super.run();
        //读取Excel数据
        readExcel(sourceFile);
        //创建sql语句
        createSql();
        //替换sql数据里面的标记
        replaceMark();
        HitUtils.exportSqlFile(mainWin.getCurrentDir(), HitConstants.EXPORT_FILE_NAME_TEST_DATA_SCRIPT, sql.toString());
        HitUtils.exportLogFile(mainWin.getCurrentDir(), HitConstants.EXPORT_FILE_NAME_TEST_DATA_LOG, exportLog.toString());
    }

    /**
     * 读取Excel获取数据
     * @param excelFile 被读取文件
     */
    @SuppressWarnings("static-access")
    private void readExcel(File excelFile){
        InputStream ins;
        try {
            ins = new FileInputStream(excelFile);
            Workbook workBook = WorkbookFactory.create(ins);
            Sheet sheet = workBook.getSheetAt(workBook.getActiveSheetIndex());
            Row row = null;
            Cell cell = null;
            // 得到最大Y坐标
            int coordinateY = sheet.getPhysicalNumberOfRows();
            pbar.setMaximum(coordinateY);
            pbar.setVisible(true);
            for(int y = 0; y < coordinateY; y++){
                row = sheet.getRow(y);
                int coordinateX = sheet.getRow(y).getPhysicalNumberOfCells();
                String rowHeadValue = HitUtils.getValueWithCell(row.getCell(0)).replace("'", "");
                if (row != null && !"".equals(rowHeadValue)) {
                    if (HitConstants.EXCEL_TABLE_NAME_MARK.equals(rowHeadValue)) {
                        createSql();
                        doClear();
                        if(cell != null){
                            cell = row.getCell(1);
                            tableName = HitUtils.getValueWithCell(row.getCell(1)).replace("'", "");
                            tmpPrintValue = tableName;
                            exportLog.append("表名" + tableName + "**********解析成功\n");
                        }
                    } else if (HitConstants.EXCEL_FIELDS_NAME_MARK.equals(rowHeadValue)) {
                        for (int x = 1; x < coordinateX; x++) {
                            cell = row.getCell(x);
                            if(cell != null){
                                fieldsName.add(HitUtils.getValueWithCell(cell).replace("'", ""));
                            }
                        }
                        tmpPrintValue = fieldsName.toString();
                        exportLog.append("列名" + tmpPrintValue + "**********解析成功\n");
                    } else if (HitConstants.EXCEL_TEST_DATA_MARK.equals(rowHeadValue)) {
                        List<String> tmpDataList = new ArrayList<String>();
                        for (int x = 1; x < coordinateX; x++) {
                            cell = row.getCell(x);
                            if(cell != null){
                                tmpDataList.add(HitUtils.getValueWithCell(cell));
                            }
                        }
                        testData.add(tmpDataList);
                        tmpPrintValue = tmpDataList.toString();
                        exportLog.append("测试数据" + tmpPrintValue + "**********解析成功\n");
                    }
                }
                // 滚屏效果
                String printedText = logArea.getText();
                String[] tmpLog = printedText.split("\n");
                if (tmpLog.length > HitConstants.LOG_ROLL_LINE_SIZE) {
                    printedText = logArea.getText().substring(
                            logArea.getText().indexOf("......") + 7, logArea.getText().length());
                } else {
                    printedText = logArea.getText();
                }
                logArea.setText(printedText + "\n" + tmpPrintValue);
                pbar.setValue(tmpPbarValue++);
                try {
                    this.sleep(HitConstants.PARSE_EXCEL_SLEEP_TIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            pbar.setVisible(false);
        } catch (Exception e) {
            e.printStackTrace();
            exportLog.append("**********资源文件解析出错**********\n" + e.toString());
            logArea.setText("**********导出测试数据失败,请查看日志**********");
            return;
        }
        logArea.setText("**********导出测试数据成功**********");
    }

    /**
     * 创建sql语句
     */
    private void createSql(){
        if (testData.size() > 0 && fieldsName.size() > 0) {
            for (List<String> testDataList : testData) {
                sql.append("delete from " + tableName + " where " + fieldsName.get(0) + " = " + testDataList.get(0) + "\n");
                sql.append("insert into " + tableName + "(");
                for (String field : fieldsName) {
                    sql.append(field + ",");
                }
                sql.delete(sql.lastIndexOf(","), sql.lastIndexOf(",") + 1);
                sql.append(") \nvalues(");
                for (String data : testDataList) {
                    sql.append( data + ",");
                }
                sql.delete(sql.lastIndexOf(","), sql.lastIndexOf(",") + 1);
                sql.append(")\n");
            }
        }
    }

    /**
     * 清除上次的读取信息
     */
    private void doClear(){
        fieldsName.clear();
        testData.clear();
    }

    /**
     * 替换测试数据中的修改时间、创建时间、修改人主键、创建人主键的标记
     */
    private void replaceMark(){
        String tmpSql = sql.toString().replace(HitConstants.EXCEL_TEST_DATA_DATATIME_MARK,
                HitConstants.DB_FUNCTION_GETDATE);
        tmpSql = tmpSql.replace(HitConstants.EXCEL_TEST_DATA_REFID_MARK, HitConstants.DB_TEST_DATA_REFID);
        sql = new StringBuilder(tmpSql);
    }
}
